package com.cmict.data.infra.service.rdbtabledraft;

import com.cmict.data.system.api.user.AdminUserApi;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import com.cmict.data.infra.controller.admin.rdbtabledraft.vo.*;
import com.cmict.data.infra.dal.dataobject.rdbtabledraft.RdbTableDraftDO;
import com.cmict.data.framework.common.pojo.PageResult;

import com.cmict.data.infra.convert.rdbtabledraft.RdbTableDraftConvert;
import com.cmict.data.infra.dal.mysql.rdbtabledraft.RdbTableDraftMapper;

import static com.cmict.data.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cmict.data.infra.enums.ErrorCodeConstants.*;

/**
 * 草稿 Service 实现类
 *
 * @author awesome1114
 */
@Service
@Validated
public class RdbTableDraftServiceImpl implements RdbTableDraftService {

    @Resource
    private RdbTableDraftMapper rdbTableDraftMapper;

    @Resource
    private AdminUserApi adminUserApi;

    @Override
    public Long createRdbTableDraft(RdbTableDraftCreateReqVO createReqVO) {
        // 插入
        RdbTableDraftDO rdbTableDraft = RdbTableDraftConvert.INSTANCE.convert(createReqVO);
        rdbTableDraftMapper.insert(rdbTableDraft);
        // 返回
        return rdbTableDraft.getId();
    }

    @Override
    public void updateRdbTableDraft(RdbTableDraftUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateRdbTableDraftExists(updateReqVO.getId());
        // 更新
        RdbTableDraftDO updateObj = RdbTableDraftConvert.INSTANCE.convert(updateReqVO);
        rdbTableDraftMapper.updateById(updateObj);
    }

    @Override
    public void deleteRdbTableDraft(Long id) {
        // 校验存在
        this.validateRdbTableDraftExists(id);
        // 删除
        rdbTableDraftMapper.deleteById(id);
    }

    private void validateRdbTableDraftExists(Long id) {
        if (rdbTableDraftMapper.selectById(id) == null) {
            throw exception(RDB_TABLE_DRAFT_NOT_EXISTS);
        }
    }

    @Override
    public RdbTableDraftDO getRdbTableDraft(Long id) {
        return rdbTableDraftMapper.selectById(id);
    }

    @Override
    public List<RdbTableDraftDO> getRdbTableDraftList(String keyword) {
        List<RdbTableDraftDO> list = rdbTableDraftMapper.selectListByKeyword(keyword);
        for (RdbTableDraftDO rdbTableDraftDO : list) {
            rdbTableDraftDO.setCreator(adminUserApi.getUser(Long.valueOf(rdbTableDraftDO.getCreator())).getCheckedData().getNickname());
        }
        return list;
    }

    @Override
    public PageResult<RdbTableDraftDO> getRdbTableDraftPage(RdbTableDraftPageReqVO pageReqVO) {
        return rdbTableDraftMapper.selectPage(pageReqVO);
    }

    @Override
    public List<RdbTableDraftDO> getRdbTableDraftList(RdbTableDraftExportReqVO exportReqVO) {
        return rdbTableDraftMapper.selectList(exportReqVO);
    }

}
